package com.haiqi.config.interceptor;

import com.haiqi.common.annotation.SafeAuthority;
import com.haiqi.modules.main.bean.MenuResponse;
import com.haiqi.modules.main.bean.ResponseBean;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.lang.annotation.Annotation;
import java.util.List;

/**
 * Created by hythzx on 2016/7/1.
 */
public class SafeAuthInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        HttpSession session = httpServletRequest.getSession();
        ResponseBean.UserBean user = (ResponseBean.UserBean) session.getAttribute("user");
        List<MenuResponse.MenusBean> menus = (List<MenuResponse.MenusBean>) session.getAttribute("menu");
        HandlerMethod handlerMethod = (HandlerMethod) o;
        Class<?> beanType = handlerMethod.getBeanType();
        Annotation annotation = beanType.getAnnotation(SafeAuthority.class);
        if(annotation != null){
            if(annotation instanceof SafeAuthority){
                SafeAuthority safeAuthority = (SafeAuthority)annotation;
                String menuCode = safeAuthority.menuCode();
                String[] menuCodeList = menuCode.split(",");
                boolean hasAuth = false;
                for (String s : menuCodeList) {
                    hasAuth = hasAuth(s, menus);
                    if(hasAuth){
                        break;
                    }
                }
                if(!hasAuth){
                    httpServletResponse.sendRedirect("/error_403");
                    return false;
                }
            }
        }else{
            httpServletResponse.sendRedirect("/error_403");
            return false;  //没有注解，不允许访问
        }
        return true;
    }

    private boolean hasAuth(String menuCode,List<MenuResponse.MenusBean> menuResponseList){
        boolean hasAuth = false;
        if(menuResponseList != null){
            for (MenuResponse.MenusBean menusBean : menuResponseList) {
                if(menusBean.getEname().equals(menuCode)){
                    hasAuth = true;
                }
            }
        }
        return hasAuth;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
